<script setup lang="ts">
  import { reactive, ref, watch, PropType } from 'vue'
  import { ElMessage, FormInstance } from 'element-plus'
  import HButton from '@/components/common/button/HButton.vue'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import {
    useNetworkOptionsService,
    useNetworkEmpOptionsService,
    useNetworkTypeOptionsService,
    useWaitCheckWorkReassignService,
  } from './services'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import { CheckWorkReassignAllow, CheckWorkReassignReject } from './types'

  const props = defineProps({
    network: {
      type: String,
      required: true,
    },
    networkId: {
      type: String,
      required: true,
    },
    orderId: {
      type: String,
      required: true,
    },
    modelValue: {
      type: Boolean,
      default: () => false,
    },
    address: Object as PropType<{
      province: string
      city: string
      area: string
      town: string
      address: string
    }>,
  })

  const emits = defineEmits<{
    (e: 'update'): void
    (e: 'update:modelValue', value: boolean): void
    (e: 'close'): void
  }>()

  // 表单
  const form = ref({
    changeToNetworkId: '',
    checkTypep: 1,
    id: '',
    networkEmpId: '',
    remark: '',
  })

  // 弹窗的显示状态
  const visible = ref(false)

  // 表单校验规则
  const rules = reactive({
    changeToNetworkId: [{ required: true, message: '请选择部门！', trigger: ['blur', 'change'] }],
  })

  // 表单组件实例
  const formRef = ref<FormInstance>()

  /**
   * 审核通过事件
   */
  const onAllow = async () => {
    if (formRef.value) {
      try {
        await formRef.value.validateField()
        const temp: CheckWorkReassignAllow = {
          changeToNetworkId: form.value.changeToNetworkId,
          remark: form.value.remark,
          id: form.value.id,
          networkEmpId: form.value.networkEmpId,
        }
        const res = await allow(temp, props.orderId)
        emits('update')
        visible.value = false
        emits('update:modelValue', visible.value)
        ElMessage({
          type: res.success ? 'success' : 'error',
          message: res.message,
          plain: true,
          duration: 5000,
          showClose: false,
        })
      } catch (e) {
        // 校验不通过
      }
    }
  }

  /**
   * 驳回审核事件
   */
  const onReject = async () => {
    const temp: CheckWorkReassignReject = {
      remark: form.value.remark,
      id: form.value.id,
    }
    const res = await reject(temp, props.orderId)
    emits('update')
    visible.value = false
    emits('update:modelValue', visible.value)
    ElMessage({
      type: res.success ? 'success' : 'error',
      message: res.message,
      plain: true,
      duration: 5000,
      showClose: false,
    })
  }

  /**
   * 取消事件
   */
  const onCancel = () => {
    form.value.changeToNetworkId = ''
    visible.value = false
    form.value.remark = ''
    form.value.networkEmpId = ''
    networkType.value = ''
    filterType.value = 0
    addr.value = {
      city: '',
      area: '',
      province: '',
      town: '',
    }
    emits('close')
    emits('update:modelValue', visible.value)
  }

  // 使用获取待审核改派部门的工单服务
  const {
    waitCheckWorkReassign,
    checkWorkReassignLoading,
    getWaitCheckWorkReassignLoading,
    allow,
    reject,
    getWaitCheckReassign,
  } = useWaitCheckWorkReassignService

  // 使用部门选项服务
  const { getNetworkOptions, getNetworkOptionsLoading, getNetworkOptionsParam, networkOptions } =
    useNetworkOptionsService

  // 使用服务人员选项服务
  const { getNetworkEmpOptions, getNetworkEmpOptionsLoading, networkEmpOptions } =
    useNetworkEmpOptionsService

  const { networkTypeOptions, getNetworkTypeOptionsLoading, getNetworkTypeOptions } =
    useNetworkTypeOptionsService

  /**
   * 获取部门选项方法
   */
  const getNetworkOptionsFn = (keyword = '') => {
    Object.assign(getNetworkOptionsParam.value, {
      area: [0, 1].includes(filterType.value) ? '' : addr.value.area,
      city: [0, 1].includes(filterType.value) ? '' : addr.value.city,
      limit: 0,
      page: 0,
      name: keyword,
      province: [0, 1].includes(filterType.value) ? '' : addr.value.province,
      type: filterType.value,
      typeId: [0, 2].includes(filterType.value) ? null : networkType.value,
    })
    if (getNetworkOptionsParam.value.typeId === '0') {
      getNetworkOptionsParam.value.typeId = ''
    }
    getNetworkOptions()
  }

  /**
   * 获取部门选项
   */
  const getNetworkOptionsKeyword = ref('')
  const callGetNetworkOptions = () => {
    getNetworkOptionsFn(getNetworkOptionsKeyword.value)
  }

  /**
   * 获取分配人员选项
   */
  const getServicePersonalOptionsKeyword = ref('')
  const callGetServicePersonOptions = () => {
    getNetworkEmpOptionsFn(getServicePersonalOptionsKeyword.value)
  }

  // 判断是否是个人
  const isTeamType = ref(false)

  /**
   * 获取服务人员选项方法
   */
  const getNetworkEmpOptionsFn = async (keyword = '') => {
    await getNetworkEmpOptions(form.value.changeToNetworkId, keyword)
    let arr = networkOptions.value.filter((o) => o.id == form.value.changeToNetworkId)
    isTeamType.value = false
    if (arr[0].teamType === 2) {
      form.value.networkEmpId = networkEmpOptions.value[0].id
      isTeamType.value = true
    }
  }

  // 部门分类
  const networkType = ref('0')

  /**
   * 获取部门类型
   */
  const getNetworkTypeOptionsKeyword = ref('')
  const callGetNetworkTypeOptions = () => {
    getNetworkTypeOptions(getNetworkTypeOptionsKeyword.value)
  }

  /**
   * 查询条件
   * 0 - 全部
   * 1 - 部门分类
   * 2 - 按省市区
   */
  const filterType = ref(0)

  // 服务范围
  const addr = ref({
    province: '',
    city: '',
    area: '',
    town: '',
  })

  // 地址组件实例
  const singleAddressRef = ref<InstanceType<typeof SingleAddress> | null>(null)

  /**
   * 获取服务范围
   */
  const handleChangeAddress = () => {
    if (singleAddressRef.value) {
      Object.assign(addr.value, singleAddressRef.value.getSelectAddr())
      callGetNetworkOptions()
    }
  }

  /**
   * 清空地址
   */
  const onClearAddress = () => {
    addr.value.province = ''
    addr.value.area = ''
    addr.value.city = ''
    addr.value.town = ''
    filterType.value = 0
    callGetNetworkOptions()
  }

  /**
   * 查询条件更新事件
   * @param {number} val - 条件的值: 1.全部 2.按部门分类 3.公司地址
   */
  const onChangeCondition = async (val: 0 | 1 | 2 | 3) => {
    if (formRef.value) {
      formRef.value.resetFields()
      addr.value.province = ''
      addr.value.area = ''
      addr.value.city = ''
      addr.value.town = ''
    }
    if (val === 3 || val === 2) {
      if (props.address) {
        filterType.value = val
        addr.value.province = props.address.province
        addr.value.city = props.address.city
        addr.value.area = props.address.area
        addr.value.town = props.address.town
      }
    }
    if (val === 1) {
      callGetNetworkTypeOptions()
    } else {
      callGetNetworkOptions()
    }
  }
  /**
   * 显示弹窗事件
   */
  const onShowModal = async () => {
    visible.value = true
    if (props.address) {
      filterType.value = 3
      addr.value.province = props.address.province
      addr.value.city = props.address.city
      addr.value.area = props.address.area
      addr.value.town = props.address.town
    } else {
      callGetNetworkTypeOptions()
    }
    callGetNetworkOptions()
  }

  /**
   * 更新部门事件
   */
  const onChangeNetwork = async () => {
    form.value.networkEmpId = ''
    callGetServicePersonOptions()
  }

  /**
   * 部门分类选择事件
   */
  const handleChangeNetworkType = () => {
    form.value.changeToNetworkId = ''
    callGetNetworkOptions()
  }

  watch(
    () => props.modelValue,
    async (value) => {
      visible.value = value
      if (value) {
        if (props.address) {
          filterType.value = 3
          addr.value.province = props.address.province
          addr.value.city = props.address.city
          addr.value.area = props.address.area
          addr.value.town = props.address.town
        } else {
          await callGetNetworkTypeOptions()
        }
        await callGetNetworkOptions()
        await getWaitCheckReassign(props.orderId)
        form.value.id = waitCheckWorkReassign.value.id
      }
    },
    { immediate: true },
  )
</script>

<template>
  <div>
    <span @click="onShowModal">
      <slot></slot>
    </span>

    <HDialog
      v-model="visible"
      title="审核改派部门申请"
      :loading="checkWorkReassignLoading || getWaitCheckWorkReassignLoading"
      @close="onCancel"
    >
      <div class="alert_container">
        <i class="iconfont icon-warning" style="color: #007cff; font-size: 18px"></i>
        <span class="text">改派后，该工单不再属于原部门</span>
      </div>
      <el-form
        ref="formRef"
        :rules="rules"
        :model="form"
        class="modal_form_content"
        label-position="top"
        inline-message
      >
        <!--当前部门-->
        <el-form-item label="当前部门">
          <el-input disabled :value="props.network" />
        </el-form-item>

        <!-- 查询条件 -->
        <el-form-item label="查询条件">
          <el-select
            v-model="filterType"
            placeholder="请选择查询条件"
            filterable
            @blur.stop="() => {}"
            @change="onChangeCondition"
          >
            <el-option :value="0" label="全部" />
            <el-option :value="1" label="按部门分类" />
            <el-option :value="2" label="服务区域" />
            <el-option :value="3" label="公司地址" />
          </el-select>
        </el-form-item>

        <!-- 服务范围 -->
        <el-form-item
          v-if="filterType === 3 || filterType === 2"
          :label="filterType === 3 ? '公司地址' : '服务区域'"
        >
          <SingleAddress
            ref="singleAddressRef"
            :address="addr"
            check-strictly
            style="width: 100%"
            @value-change="handleChangeAddress"
            @clear="onClearAddress"
          />
        </el-form-item>

        <!-- 部门分类 -->
        <el-form-item v-if="filterType === 1" label="部门分类">
          <el-select
            v-model="networkType"
            placeholder="部门分类"
            :loading="getNetworkTypeOptionsLoading"
            @change="handleChangeNetworkType"
          >
            <template #header>
              <div class="select_header">
                <el-input
                  v-model.trim="getNetworkTypeOptionsKeyword"
                  placeholder="请输入关键字"
                  @keyup.enter="callGetNetworkTypeOptions"
                />
                <HPlainButton @click="callGetNetworkTypeOptions">搜索</HPlainButton>
              </div>
            </template>
            <el-option value="0" label="全部" />
            <el-option
              v-for="item in networkTypeOptions"
              :key="item.name"
              :disabled="networkId === item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>

        <!-- 分配部门 -->
        <el-form-item label="分配部门" required prop="changeToNetworkId">
          <el-select
            v-model="form.changeToNetworkId"
            placeholder="分配部门"
            :loading="getNetworkOptionsLoading"
            @change="onChangeNetwork"
          >
            <template #header>
              <div class="select_header">
                <el-input
                  v-model.trim="getNetworkOptionsKeyword"
                  placeholder="请输入关键字"
                  @keyup.enter="callGetNetworkOptions"
                />
                <HPlainButton @click="callGetNetworkOptions">搜索</HPlainButton>
              </div>
            </template>
            <el-option
              v-for="(item, index) in networkOptions"
              :key="index"
              :disabled="networkId === item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>

        <!-- 分配人员 -->
        <el-form-item v-if="!isTeamType" label="分配人员">
          <el-select
            v-model="form.networkEmpId"
            placeholder="分配人员"
            :loading="getNetworkEmpOptionsLoading"
            clearable
          >
            <template #header>
              <div class="select_header">
                <el-input
                  v-model.trim="getServicePersonalOptionsKeyword"
                  placeholder="请输入关键字"
                  @keyup.enter="callGetServicePersonOptions"
                />
                <HPlainButton @click="callGetServicePersonOptions">搜索</HPlainButton>
              </div>
            </template>
            <el-option
              v-for="item in networkEmpOptions"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model.trim="form.remark"
            maxlength="200"
            placeholder="请输入备注"
            show-word-limit
            type="textarea"
            resize="both"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <HPlainBgButton is-modal type="error" @click="onReject">驳回</HPlainBgButton>
        <HButton is-modal type="primary" @click="onAllow">审核通过</HButton>
        <HButton is-modal @click="onCancel">取消</HButton>
      </template>
    </HDialog>
  </div>
</template>

<style scoped lang="scss">
  @import './CheckUpdateNetwork.scss';
</style>
